package br.org.ielbilha.manager.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

@Stateless
public class CrudService {

	@Resource(name="util/DozerMapper", type=DozerBeanMapper.class, shareable=true)
	private static Mapper mapper;

	@PersistenceUnit(unitName="IelbPU")
	private EntityManager em;

	/* (non-Javadoc)
	 * @see br.org.ielbilha.manager.service.CrudInterface#insert(java.lang.Object)
	 */
	public void insert(final Object dto) throws ClassNotFoundException{

		final String pojoClassName = this.getPojoName(dto);
		final Class pojoClass = Class.forName(pojoClassName);
		final Object pojo = CrudService.mapper.map(dto, pojoClass);

		this.em.persist(pojo);
		this.em.flush();
	}

	/* (non-Javadoc)
	 * @see br.org.ielbilha.manager.service.CrudInterface#alter(java.lang.Object)
	 */
	public void alter(final Object dto) throws ClassNotFoundException{

		final String pojoClassName = this.getPojoName(dto);
		final Class pojoClass = Class.forName(pojoClassName);

		final Object pk = this.getPk(pojoClass, dto);
		final Object pojo = this.em.find(pojoClass, pk);

		CrudService.mapper.map(pojo,dto);

		this.em.persist(pojo);
		this.em.flush();
	}

	/* (non-Javadoc)
	 * @see br.org.ielbilha.manager.service.CrudInterface#delete(java.lang.Object)
	 */
	public void delete(final Object dto) throws ClassNotFoundException{

		final String pojoClassName = this.getPojoName(dto);
		final Class pojoClass = Class.forName(pojoClassName);

		final Object pk = this.getPk(pojoClass, dto);
		final Object pojo = this.em.getReference(pojoClass, pk);

		this.em.remove(pojo);
		this.em.flush();
	}

	/* (non-Javadoc)
	 * @see br.org.ielbilha.manager.service.CrudInterface#list(java.lang.Object)
	 */
	public List list(final Object dto) throws ClassNotFoundException{

		final String pojoClassName = this.getPojoName(dto);
		final Class pojoClass = Class.forName(pojoClassName);

		final Object pk = this.getPk(pojoClass, dto);
		final Object pojo = this.em.find(pojoClass, pk);

		CrudService.mapper.map(pojo,dto);

		final Query query = this.em.createQuery(this.getSimpleFilterQuery(pojo));
		final List ret = new ArrayList();

		for(final Object o : query.getResultList())
			ret.add(CrudService.mapper.map(o, pojoClass));

		return ret;

	}

	private String getSimpleFilterQuery(final Object pojo) {
		// TODO Auto-generated method stub
		return null;
	}

	private Object getPk(final Class pojoClass, final Object dto) {
		// TODO Auto-generated method stub
		return null;
	}

	private String getPojoName(final Object dto) {
		// TODO Auto-generated method stub
		return null;
	}
}
